﻿using System;
using System.Collections.ObjectModel;

namespace MvvmBase.ViewModel
{
    public class ModelJob
    {
        private readonly ModelJobEntry _entry;
        private readonly ObservableCollection<ModelJobEntry> _jobQueue;
        internal ModelJob(ObservableCollection<ModelJobEntry> jobQueue, ModeJobMode mode)
        {
            _jobQueue = jobQueue;
            _entry = new ModelJobEntry(this, mode);
            _jobQueue.Add(_entry);
        }

        public event EventHandler Released;
        public bool IsCanceled { get; private set; }
        public virtual void Release()
        {
            ReleaseAndCallEvent();
        }

        public void Cancel()
        {
            if (!IsCanceled)
                IsCanceled = true;
        }

        protected void ReleaseAndCallEvent()
        {
            _jobQueue.Remove(_entry);
            OnReleased();
        }

        private void OnReleased()
        {
            EventHandler handler = Released;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }
    }
}